<template>
    <div v-loading="loading" element-loading-text="登录中..." element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.6)" class="login-container" :style="bg">

        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
                 label-position="left">
            <div class="title-container">
                <h3 class="app-title">{{ this.$store.state.app.name }}</h3>
            </div>

            <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large" tabIndex="-1"/>
            </el-form-item>
            <el-form-item prop="password">
                <el-input ref="password"
                          v-model="loginForm.password" size="large" show-password
                          placeholder="请输入密码" name="password" tabIndex="-1" auto-complete="on"
                          @keyup.enter="handleLogin"
                />
            </el-form-item>

            <div>
                <el-button type="primary" class="login-btn"
                           @click.native.prevent="handleLogin"
                           @keyup.enter.prevent="handleLogin">
                    登录
                </el-button>
            </div>
        </el-form>
    </div>

    <el-footer class="footer">
        <div class="footer-company">
            Copyrint © {{ year }}
            <a href="http://beian.miit.gov.cn/" class="beian">豫ICP备2024049084号-4</a>
        </div>
    </el-footer>
</template>

<script>
import {userLogin} from "@/api/user";
import {encryptData} from "@/utils/crypto.js";

export default {
    name: 'Login',
    data() {
        const validateUsername = (rule, value, callback) => {
            if (!value) {
                callback(new Error('用户名不能为空！'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (value.length < 3) {
                callback(new Error('密码最少为6位字符！'))
            } else {
                callback()
            }
        }
        return {
            // 登录表单
            loginForm: {
                username: '',
                password: ''
            },
            // 登录规则
            loginRules: {
                username: [{required: true, trigger: 'blur', validator: validateUsername}],
                password: [{required: true, trigger: 'blur', validator: validatePassword}]
            },
            loading: false,
            year: new Date().getFullYear(),
            bg: {
                'background-image': 'url("/bg/' + Math.floor(Math.random() * 12 + 1) + '.jpg")',
                'background-size': 'cover'
            }
        }
    },
    mounted() {
        this.handleIsLogin()
    },

    methods: {
        handleIsLogin() {
            // 判断localStroge中是否有token
            let user = JSON.parse(localStorage.getItem('user'))
            let token = localStorage.getItem('token')
            if (user && token) {
                this.$store.commit('SET_USERINFO', user)
                this.$store.commit('SET_TOKEN', token)
                this.$message({
                    message: '自动登录成功',
                    type: 'success',
                    duration: 1000,
                    onClose: () => {
                        this.$router.push({path: '/index'})
                    }
                })
            }
        },

        // 登录业务
        handleLogin() {
            this.$refs.loginForm.validate((valid) => {
                // 如果符合验证规则
                if (valid) {
                    this.loading = true
                    // 发送登录请求
                    let params = JSON.parse(JSON.stringify(this.loginForm))
                    params.password = encryptData(params.password)
                    userLogin(params).then((res) => {
                        console.log(res)
                        this.loading = false
                        if (res.code === 200) {
                            //保存token
                            this.$store.commit('SET_TOKEN', res.data.token)
                            this.$store.commit('SET_USERINFO', res.data)
                            this.$message({
                                message: '登录成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.$router.push({path: this.redirect || '/index'})
                                }
                            })
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error',
                                duration: 1500
                            })
                        }
                    }).catch((result) => {
                        console.log(result)
                        this.loading = false
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        }
    }
}
</script>


<style>
.login-container {
    display: flex;
    justify-content: center;
    align-self: center;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.title-container {
    margin: 30px auto;
}

.login-form {
    width: 500px;
    margin: 0 auto;
    padding: 20px;
    border-radius: 5px;
    background-color: #fff;
}

.app-title {
    text-align: center;
}

.login-btn {
    width: 100%;
    margin-bottom: 20px;
}

.footer {
    width: 100%;
    height: 20px;
    text-align: center;
    font-size: 14px;
    color: #000000;
    position: fixed;
    bottom: 30px;
}

.footer-company {
    color: white;
    width: 380px;
    margin: 0 auto;
}

.footer-company a {
    color: white;
}

.beian {
    text-decoration: none;
}
</style>